load('js/v6/abc/abc_collect_data.js');
load('js/v6/abc/abc_crawl_data.js');
load('js/v6/abc/abc_common.js');
load('js/v6/abc/abc_lua.js');
load("js/luaclient.js");
load("js/keys_comm.js");
var loginAfterStatus = "";
var debitResultList = new ArrayList();
var creditResultList = new ArrayList();
var depositList = new ArrayList();
var creditCardAllData;
var deditCardAllData;
var showTimes;
/**
 * 农行抓取请求入口
 * @type {{}}
 */
var v6_abc_java_funcs = {
    openHomePage: function () {
        var loginHtml = urls.REQ_LOGIN_HTML_URL;
        //访问首页
        var indexHtml = get(loginHtml);
        storeDataToFile(context, indexHtml, "index.html");
        //页面不为空
        context.put("indexHtml", indexHtml)
    },
    checkProxyAvailable: function () {
        var isCorrectFunc = function(){
            return checkElementIsExist( "username");
        }

        var getErrorMsgFunc = function() {
            return "代理ip异常";
        }

        return assertTrueOrThrowException("", isCorrectFunc, getErrorMsgFunc);
    },
    checkTargetWebsiteAvailable: function () {
        return true
    },
    checkControlAvailable: function () {
        return true
    },
    //只有在图片验证码错误或短信验证码错误　　重置环境
    needResetEnvironment: function () {
        return equals(context.get("currentErrorCode"), BALO_99602_50) || equals(context.get("currentErrorCode"), BALO_99602_40);
    },
    login: function () {
        //输入用户明密码
        inputBase();
        // 输入图片验证码和登录
        inputImg();
        // 跳转时尚版首页
    },
    //抓取过程
    crawl: function () {
        logger.info("农业银行:taskKey:{},开始抓取" ,context.get(LUA_TASK_KEY));
        if (!equals("HASINMAIN", loginAfterStatus)) {
            logger.info("农业银行:taskKey=" + context.get(LUA_TASK_KEY) + ",开始抓取经典版");
            // 经典版暂不抓取
            //经典版抓取借记卡的方法
            // 采集经典版基本信息
            collectReqData.collectSutraBasicCardInfoList();
            crawlReqData.crawlSutraBasicCardInfoList();
            var basic_card_info_list = context.get("basic_card_info_list");
            for (var cardIndex = 0; cardIndex < basic_card_info_list.size(); cardIndex++) {
                var basic_card_info = basic_card_info_list.get(cardIndex);
                creditCardAllData = new CreditCardAllData();
                crawlReqData.saveSutraBasicInfo(creditCardAllData,basic_card_info);
                // 采集卡基本信息
                collectReqData.collectSutraBasicCardInfo(cardIndex);
                // 抓取卡基本信息
                crawlReqData.crawlSutraBasicCardInfo();

            }
            //抓取卡类表信息和用户基本信息
        } else {
            //根据上下文的卡数量，初始化对应的封装对象，供全局使用
            // ------前置URL --进入首页
            collectReqData.collectFashionCardList();
            // 抓取首页信息
            crawlReqData.crawlFashionCardList();
            var debitCardList = context.get(keys.DEBT_CARD_LIST);
            var creditCardList = context.get(keys.CRED_CARD_LIST);
            var debitCardListSize = debitCardList.size();//借记卡个数
            var creditCardListSize = creditCardList.size();//信用卡个数
            // createData();//创建表头
            logger.info("农业银行 taskkey:{},当前账户抓取到{}张卡，{}张借记卡，{}张信用卡，停止抓取",
                        context.get(LUA_TASK_KEY),debitCardListSize + creditCardListSize,debitCardListSize,creditCardListSize);
            if (debitCardListSize==0) {
                logger.info("农业银行 taskkey:{},当前账户没有获取到借记卡卡号相关信息，停止抓取",context.get(LUA_TASK_KEY));
                return;
            }
            // 采集卡列表信息
            collectReqData.collectFashionAccountCardInfo();
            //解析卡列表信息
            var basicLsit = crawlReqData.crawlFashionAccountCardInfo();
            if (basicLsit == null || basicLsit.size() == 0) {
                logger.info("借记卡账户基本信息为空，停止抓取借记卡");
                return;
            }
            for (var depositCardIndex = 0; depositCardIndex < basicLsit.size(); depositCardIndex++) {
                var basicInfo = basicLsit.get(depositCardIndex);
                var cardNo = basicInfo.getString("acctNo");
                // 封装creditCardAllData
                deditCardAllData = new CreditCardAllData();
                // 获取卡号信息
                crawlReqData.saveCreditCardAllData(deditCardAllData, basicInfo,cardNo,"DEBIT");
                // 采集用户存款信息
                collectReqData.collectFashionDepsoitInfo(basicInfo, depositCardIndex);
                // 采集用户存款信息
                collectReqData.collectFashionSubCardInfo(basicInfo, depositCardIndex);
                // 抓取用户存款信息 现在未完成
                crawlReqData.carwlFashionDepsoitInfo(deditCardAllData, depositCardIndex);
                // 采集用户存款信息,采集6个月的
                //账单信息  循环抓取六个月的账单信息
                var calendar=Calendar.getInstance();
                var currentMonth = calendar.get(Calendar.MONTH) + 1;
                for (var motheIndex = 0; motheIndex < 6; motheIndex++) {
                    //获取6个月，前六个月第一天，最后一天
                    var dateList=commonUtils.get6MonthStartAndEnd(currentMonth, calendar);
                    // var dateList = commonUtils.getFirstDayAndLastDay(motheIndex);
                    // 采集用户月账单数据
                    collectReqData.collectFashionMonthBillData(basicInfo,dateList);
                    // 抓取用户月账单数据
                    crawlReqData.crawlDepsoitBillOnNewEdition(deditCardAllData,basicInfo,dateList);

                }
                depositList.add(deditCardAllData);
            }
            //context.put(DEBIT_DATA,debitResultList);

            //循环抓取卡列表
            for(var creditIndex=0;creditIndex<creditCardList.size();creditIndex++){
                var fullCardNum = creditCardList.get(creditIndex);
                // var fullCardNum=basicInfoJsonObject.getString("acctNo");
                logger.info("农业银行 taskkey：{}，抓取第{}卡号为{}的账户信息",context.get(LUA_TASK_KEY),creditIndex+1);
                creditCardAllData = new CreditCardAllData();
                crawlReqData.saveCreditCardAllData(creditCardAllData, fullCardNum,"CREDIT");
                // 采集用户信用基本信息
                collectReqData.collectCreditCardInfo(fullCardNum);
                // 抓取用户信用卡基本信息
                crawlReqData.crawlCreditCardInfo(creditCardAllData);
                // 采集信用卡可查询的已出账单月份
                collectReqData.collectCreditDoneBills(creditIndex,fullCardNum);
                // 抓取信用卡可查询的已出账单月份
                crawlReqData.crawlCreditDoneBills(creditIndex,fullCardNum);
                // 获取可查询的账单月份
                var queryMonthList = context.get(creditIndex+"queryMonthList");
                for(var queryMonthIndex = 0;queryMonthIndex < queryMonthList.size();queryMonthIndex++){
                    var queryMonthInfo = queryMonthList.get(queryMonthIndex);
                    var billDate = queryMonthInfo.getString("billDate");//账单日
                    // 获取每月账单日
                    if(StringUtils.isNotBlank(billDate)){
                        var billDays = billDate.substring(6,8);
                        context.put("billDays",billDays);
                    }
                    var billMonth = queryMonthInfo.getString("billMonth");//账单月
                    var billAllData = new BillAllData();
                    if(billDate != undefined){
                        // 采集月账单信息
                        collectReqData.collectCreditQueryMonthDoneBill(creditIndex,billDate,billMonth,creditBasicInfo);
                        // 抓取月账单类表信息
                        crawlReqData.crawlCreditQueryMonthDoneBill(billAllData,creditIndex,fullCardNum,billMonth,billDate);
                        // 采集账单详细信息数据
                        collectReqData.collectCreditDoneBillInfo(creditIndex,fullCardNum,billDate);
                        // 抓取账单详细信息数据
                        crawlReqData.crawlCreditDoneBillInfo(billAllData,creditIndex,fullCardNum,billDate);
                        // 采集信用卡账单数据总的分期数据明细
                        collectReqData.collectCreditDoneInstallmentInfo(creditIndex,fullCardNum,billDate);
                        // 采集信用卡账单数据总的分期数据明细
                        crawlReqData.crawlCreditDoneInstallmentInfo(billAllData,creditIndex,fullCardNum,billDate);
                    }
                }
                //采集未出账单数据
                collectReqData.collectCreditUndoneBills(creditIndex,fullCardNum);
                //抓取未出账单数据
                var unBillAllData = new BillAllData();
                //抓取未出账单数据
                crawlReqData.crawlCreditUndoneBills(creditCardAllData,unBillAllData,creditIndex);
                depositList.add(creditCardAllData)
            }
            context.put(ALL_DATA,depositList);
        }

    },
    exitLogin: function () {
    }

};

/**
 * 输入用户名、密码
 */
function inputBase() {
    var  lockFlag = lock.isHeldByCurrentThread() ;
    if (lockFlag) {
        logger.info("abc taskKey = {} 当前线程已经持有锁，无需再次获取锁",context.get(LUA_TASK_KEY));
    }else {
        logger.info("abc taskKey = {} 当前线程没有持有锁，等待获取锁",context.get(LUA_TASK_KEY));
        lock.lock();
    }
    luaFuncs.setSize();
    // var loginUrl = "https://perbank.abchina.com/EbankSite/startup.do";
    // //这里使用js的跳转页面方法
    // luaFuncs.jumpByUrl(loginUrl);
    logger.info("农业银行 taskKey = {} 检查密码是否合法" ,context.get(LUA_TASK_KEY));
    var password = context.get(LUA_TASK_TOKEN);
    //检查密码是否合法
    checkLoginTextLegal(password,"password");
    logger.info("任务taskKey = {}, 显示窗口", context.get(LUA_TASK_KEY));
    showTimes = System.nanoTime();
    var kongge= /\s+/g;//空格正则表达式
    var username =getLoginParams(context)[0];
    username = username.replace(kongge,"");//去除所有空格
    checkLoginTextLegal(username,"username");//TODO 这里需要重新改变
    // var status=luaFuncs.loginUsernameAndPassowrd(username, password, context.get(LUA_TASK_KEY));
    var statuts=checkPassCompleteInThree(username, password);
    showTimes = System.nanoTime() - showTimes;
    logger.info("任务 taskKey = {} , 窗口显示时间：{}",context.get(LUA_TASK_KEY), showTimes);
    logger.info("农业银行:taskKey=" + context.get(LUA_TASK_KEY) + "输入用户名和密码，lua返回的状态码是" + statuts);
    var loginFlag = false;
    if(equals(statuts.toLowerCase(),"ok")){
        loginFlag = true;
    }
    commonUtils.isValidThorwError(loginFlag,"密码因控件输入错误");
}

/**
 * 获取图片验证码和登录
 */
function inputImg() {
    var taskKey = context.get(LUA_TASK_KEY);
    logger.info("农业银行: taskKey =" + taskKey + "Lua获取验证码图片");
    var validateImPath= get_image_by_id("vCode");
    var validImg = false;
    if (!validateImPath.contains("path fail")) {
        validImg = true;
    }
    commonUtils.isValidThorwError(validImg,"图片验证码获取失败");
    context.put(TASK_IMG_PATH, validateImPath);
    context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");
    var captchaResult = waitImgCodeBySecondsByJs(context,60,true,3);
    if(captchaResult.length == 4){
        validImg = true;
    }
    commonUtils.isValidThorwError(validImg,"图片验证码错误");
    // 输入图片验证码 这个在lua中整合成一个方法
    logger.info("验证码 结果{} 输入图片验证码", captchaResult);
    var isInputCode = luaFuncs.abcSetInputEvent(captchaResult, 'code');
    // var isInputCode = set_input_text_by_id("code",captchaResult);
    // var inputCodeResult = luaFuncs.input_text_by_id_event("id",captchaResult);
    var isFlag = false;
    if(equals(isInputCode.toLowerCase(),"ok")){
        isFlag = true;
    }
    commonUtils.isValidThorwError(isFlag,"图片验证码错误");
    show();
    // 点击登录按钮同事获取错误信息
    logger.info("农业银行:taskKey=" + taskKey + "点击登录");
    // var loginFlag = luaFuncs.loginCheckCode(captchaResult);
    click_by_id("logo");
    //是否跳转页面
    var logoUrl = luaFuncs.waiting_Goto(15000);
    if(logoUrl.contains("正在登陆")){
        logger.info("农业银行:taskKey=" + taskKey + "正在登陆。。。");
        logoUrl = luaFuncs.waiting_Goto(35000);
    }
    screen_print();
    var isLogin = false;
    var loginSeccessHtml = get_html();
    var loginToUrl = get_url();
    logger.info("农业银行:taskKey={}，点击登录后获取的URL：{} ",taskKey,loginToUrl);
    // var toLoginHtml =  get_html2();
    var loginClickHtml = Jsoup.parse(loginSeccessHtml);
    var loginUrl = "https://perbank.abchina.com/EbankSite/startup.do";
    if(loginToUrl.contains(loginUrl)){
        logger.info("农业银行:taskKey=" + taskKey + "未登陆成功");
        screen_print();
        var loginErrorMassge ="";
        loginErrorMassge = loginClickHtml.select("#username-error").text();
        if(StringUtils.isNotBlank(loginErrorMassge)){
            logger.info("农业银行:taskKey=" + taskKey + "loginErrorMassge:{}",loginErrorMassge);
            commonUtils.isValidThorwError(isLogin,loginErrorMassge);
        }
        loginErrorMassge = loginClickHtml.select("#lpowerpass_ie_dyn_Msg").text();
        if(StringUtils.isNotBlank(loginErrorMassge)){
            logger.info("农业银行:taskKey=" + taskKey + "loginErrorMassge:{}",loginErrorMassge);
            commonUtils.isValidThorwError(isLogin,loginErrorMassge);
        }
        loginErrorMassge = loginClickHtml.select(".logon-error").get(0).text();
        if(StringUtils.isNotBlank(loginErrorMassge)){
            logger.info("农业银行:taskKey=" + taskKey + "loginErrorMassge:{}",loginErrorMassge);
            commonUtils.isValidThorwError(isLogin,loginErrorMassge);
        }
        logger.info("农业银行:taskKey=" + taskKey + "loginErrorMassge:{}","登录超时");
        commonUtils.isValidThorwError(isLogin,"登录超时");
    }
    screen_print();
    if(loginSeccessHtml.contains("密码过于简单")){
        lock.unlock();
        logger.info("农业银行:taskKey=" + taskKey + ",密码设置过于简单，请重置");
        commonUtils.isValidThorwError(isLogin,"密码设置过于简单，请重置");
    }else if (loginSeccessHtml.contains("中国农业银行个人网银首页")) {
        lock.unlock();
        logger.info("农业银行:taskKey=" + taskKey + ",登陆成功，中国农业银行个人网银首页");
        loginAfterStatus="HASINMAIN";
        logger.info("当前用户无需短信或者其他验证，已经进入主页,不能进行经典版的跳转");
    }else{
        lock.unlock();
        logger.info("农业银行:taskKey=" + taskKey + ",登陆成功，跳转经典版首页进行抓取");
        // 旧版的页面地址
        var oldUrl = urls.REQ_CLASSIC_INDEX_URL;
        luaFuncs.jumpByUrl(oldUrl)
        // 跳转成功后点击时尚版进入到时尚版页面进行抓取
        // $(".logo03")[0].getElementsByTagName("span")[0].getElementsByTagName("a")[0].click()
        // https://perbank.abchina.com/EbankSite/autoLogin.do
        var fashionUrl = luaFuncs.click_fashion_button();
        logger.info("农业银行:taskKey={},登陆成功，跳转经典版首页后跳转时尚版的Url：{}",taskKey,fashionUrl);
        if(fashionUrl.contains(urls.REQ_CLASSIC_JUMP_FASHION_URL)){
            loginAfterStatus="HASINMAIN";
        }
    }
    hide();
    screen_print();

}
/**
 * 判断页面是否加载完全，如果不是则刷新页面三次
 *
 * @param client
 * @param Id
 * @return
 * @throws InterruptedException
 */
function  checkElementIsExist(Id)  {
    var flag = is_exist_by_id(Id);
    for (var i = 1; i < 4; i++) {
        if (flag) {
            break;
        }
        logger.info("农业银行:taskKey=" + context.get(LUA_TASK_KEY) + "页面指定ID不存在，第" + i + "次刷新页面");
        refresh();
        Thread.sleep(3000);
        var html = luaFuncs.getHtmlGb2312();
        storeDataToFile(context,html, i + "_loginHtml.html");
        flag = is_exist_by_id(Id);
    }
    return flag;
}
/**
 * 检查登录的元素是否合法
 * @param password
 * @param loginFlag
 */
function checkLoginTextLegal(password,flag) {

    var patter = "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘’；：”“'。，、？%+\\\\·]";
    //经验证，用户名长度最少为两位
    if (equals("username",flag)) {
        if (password.length < 2) {
            logger.info("当前用户名长度不够，其长度为{}", password.length);
            lock.unlock();
            throw new BankException(BankConstants.BALO_22001_10, "用户名长度不够，停止输入");
        } else if (password.match(patter)) {
            logger.info("用户名包含不合法字符，用户名为{}", password);
            lock.unlock();
            throw new BankException(BankConstants.BALO_22001_10, "用户名包含不合法字符，停止输入");
        }
    }
    if (equals("password",flag)){
        if (password.length<6){
            logger.info("当前密码长度不够，其长度为{}",password.length);
            lock.unlock();
            throw new BankException(BankConstants.BALO_22001_10, "用户密码长度不够，停止输入");
        }else if (password.match(patter)){
            logger.info("abc taskKey = {} 当前用户含有非法字符，停止抓取",context.get(LUA_TASK_KEY));
            lock.unlock();
            throw new BankException(BankConstants.BALO_22001_10, "用户密码包含非法字符，停止输入");
        }
    }
}
/**
 * 检查密码输入三次，如果没有输入进入三次重试
 */
function checkPassCompleteInThree(username,password) {
    var taskKey=context.get(LUA_TASK_TOKEN);
    var status="OK";
    for(var i=1;i<4;i++){
        logger.info("农业银行 taskKey={}开始输入用户名和密码",taskKey);
        show();
        status=luaFuncs.loginUsernameAndPassowrd(username, password, taskKey);
        hide();
        logger.info("农业银行taskKey={}第{}次输入密码返回的状态码为{}",taskKey,i,status);
        if(equals("OK",status)){
            return status;
        }else{
            logger.info("农业银行taskKey={}第{}次输入密码不完整,需要重新输入",taskKey,i,status);
            var aa=luaFuncs.abcRefresh();
        }
    }
    logger.info("农业银行 taskKey= {} 输入三次之后返回的状态为{}",taskKey,status);
    return status;
}
/**
 * 根据密码长度来获取*的长度
 * @param password
 * @return
 */
function getAnonymousString(password) {
    var anonymousPasswd="";
    if (password!==null && password.length>0) {
        for (var i = 0; i < password.length; i++) {
            anonymousPasswd=anonymousPasswd+"*";
        }
    }
    return anonymousPasswd;
}